package xyz.tommy0607.codepedia_helper.action;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.intellij.codeInsight.daemon.impl.HintRenderer;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.JBColor;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.jetbrains.annotations.NotNull;
import xyz.tommy0607.codepedia_helper.Main;
import xyz.tommy0607.codepedia_helper.Main.ShowAnnosGutterIconRenderer;

import java.awt.*;
import java.io.IOException;
import java.util.Map;

public class NewAnnotationAction extends AnAction {

    public NewAnnotationAction() {
        super();
    }

    @Override
    public void update(@NotNull AnActionEvent e) {
        Project project = e.getProject();
        e.getPresentation().setEnabledAndVisible(project != null
                && Main.getInstance(project) != null && Main.getInstance(project).hasLogin);
    }

    public void actionPerformed(AnActionEvent event) {
        Project project = event.getProject();
        VirtualFile currentFile = event.getData(PlatformDataKeys.VIRTUAL_FILE);
        final Editor editor = event.getData(CommonDataKeys.EDITOR);
        Integer fileID = currentFile.getUserData(Main.FILE_ID_KEY);
        int lineNumber = editor.getCaretModel().getLogicalPosition().line + 1;
        InlayModel inlayModel = editor.getInlayModel();
        MarkupModel markupModel = editor.getMarkupModel();
        Map<Integer, Inlay<HintRenderer>> myAnnotationsInlay = editor.getUserData(Main.MY_ANNOTATION_INLAY_KEY);
        Map<Integer, RangeHighlighter> myAnnotationsHighlighter = editor.getUserData(Main.MY_ANNOTATION_HIGHLIGHTER_KEY);
        Map<Integer, RangeHighlighter> showAnnosIcon = editor.getUserData(Main.SHOW_ANNOTATIONS_ICON_KEY);
        //因为showAnnosIcon不为空，那么前面两个Map也肯定获取完毕了
        if (showAnnosIcon != null) {
            try {
                String annotation = Messages.showInputDialog("Type your annotation for the line", "New Annotation", Messages.getInformationIcon());
                RequestBody requestBody = new FormBody.Builder()
                        .add("file_id", String.valueOf(fileID))
                        .add("linenum", String.valueOf(lineNumber))
                        .add("content", annotation)
                        .build();
                Request request = new Request.Builder()
                        .url("http://codepedia.trustie.net/operations/add_annotation/")
                        .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
                        .addHeader("Cookie", "sessionid=" + Main.getInstance(project).sessionID)
                        .post(requestBody)
                        .build();
                Response response = Main.getInstance(project).okHttpClient.newCall(request).execute();
                if (response.isSuccessful()) {
                    JSONObject json = JSON.parseObject(response.body().string());
                    String msg = json.getString("msg");
                    if (json.getString("status").equals("success")) {
                        Messages.showInfoMessage("Add annotation successfully.", "");
                        int lineStartOffset = editor.getDocument().getLineStartOffset(lineNumber - 1);
                        Inlay<HintRenderer> inlay = inlayModel.addAfterLineEndElement(lineStartOffset, false, new HintRenderer("// " + annotation));
                        RangeHighlighter highlighter = markupModel.addLineHighlighter(lineNumber - 1, 5000, new TextAttributes(null, JBColor.GREEN, null, null, Font.PLAIN));
                        myAnnotationsInlay.put(lineNumber, inlay);
                        myAnnotationsHighlighter.put(lineNumber, highlighter);
                        RangeHighlighter iconHighlighter = showAnnosIcon.get(lineNumber);
                        if (iconHighlighter != null) {
                            ((ShowAnnosGutterIconRenderer)iconHighlighter.getGutterIconRenderer()).increase();
                        } else {
                            ShowAnnosGutterIconRenderer icon = new ShowAnnosGutterIconRenderer(lineNumber, 1);
                            iconHighlighter = markupModel.addLineHighlighter(lineNumber - 1, 5000, new TextAttributes(null, JBColor.GREEN, null, null, Font.PLAIN));
                            iconHighlighter.setGutterIconRenderer(icon);
                        }
                    } else if (msg.contains("未登陆")) {
                        Messages.showErrorDialog("The login session is invalid now, please login again.", "");
                    } else if (msg.contains("添加过注释")) {
                        Messages.showErrorDialog("You can only add one annotation for each line.", "");
                    } else {
                        Messages.showErrorDialog(msg, "");
                        System.out.println(json);
                    }
                } else {
                    Messages.showErrorDialog("Fail to add annotation", "Error");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}